package com.ll.sender.impl;

import java.util.Properties;

import javax.mail.AuthenticationFailedException;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.ll.exception.UserException;
import com.ll.exception.UserExceptionConstants;
import com.ll.sender.MailAuthenticator;
import com.ll.sender.SendEmailFactory;
@Service
public class SmtpSend implements SendEmailFactory {

	private static Logger LOGGER = LoggerFactory.getLogger(SmtpSend.class);

	/**
	 * 发送邮件的props文件
	 */
	private final transient Properties props = System.getProperties();
	/**
	 * 邮件服务器登录验证
	 */
	private transient MailAuthenticator authenticator;

	/**
	 * 邮箱session
	 */
	private transient Session session;

	@Override
	public void send(String address,Integer port, String username, String password, String recipient, String subject, String content) {
		try {
			// 初始化props
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.host", address);
			props.put("mail.smtp.port", port);
			// 验证
			authenticator = new MailAuthenticator(username, password);
			// 创建session
			session = Session.getInstance(props, authenticator);

			// 创建mime类型邮件
			final MimeMessage message = new MimeMessage(session);
			// 设置发信人
			message.setFrom(new InternetAddress(authenticator.getUsername()));
			// 设置收件人
			message.setRecipient(RecipientType.TO, new InternetAddress(recipient));
			// 设置主题
			message.setSubject(subject);
			// 设置邮件内容
			message.setContent(content.toString(), "text/html;charset=utf-8");
			// 发送
			Transport.send(message);
		} catch (AddressException e) {
			LOGGER.error(UserExceptionConstants.ADDRESSEXCEPTION.getErrorMsg(), e);
			throw new UserException(UserExceptionConstants.ADDRESSEXCEPTION, e);
		} catch (AuthenticationFailedException e) {
			LOGGER.error(UserExceptionConstants.AUTHENTICATIONFAILEDEXCEPTION.getErrorMsg(), e);
			throw new UserException(UserExceptionConstants.AUTHENTICATIONFAILEDEXCEPTION, e);
		} catch (MessagingException e) {
			LOGGER.error(UserExceptionConstants.MESSAGINGEXCEPTION.getErrorMsg(), e);
			throw new UserException(UserExceptionConstants.MESSAGINGEXCEPTION, e);
		}
	}

}
